#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h> 
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>

using namespace std;
const int MAX_NUM = 1024;
#define SEP " "
//define DEBUG 1

#define NoneRedir   0
#define OutputRedir 1
#define AppendRedir 2
#define InputRedir  3

char cwd[1024];
char enval[1024][100];
int envnum = 0;
char* filename = NULL;
int lastcode = 0;
int redir = NoneRedir;
const int SIZE = 64;
const char *homepath()
{
    const char*home = getenv("HOME");
    if(home) return home;
    return ".";
}
const char* getUsername()
{
    const char *name = getenv("USER");
    if(name) return name;
    return "none";
}
const char *getHostname()
{
    const char *hostname = getenv("HOSTNAME");
    if(hostname) return hostname;
    else return "none";
}

const char* getCwd()
{
    const char *cwd = getenv("PWD");
    if(cwd) return cwd;
    else return "none";
}
int getCommand(char* Command, int num)
{
    printf("[%s@%s %s]& ", getUsername(), getCwd(), getCwd());
    char *r = fgets(Command, num, stdin);                                             
    if(!r) return -1;                                                                                      
    Command[strlen(Command) - 1] = '\0';                                                                                                                                      
    return strlen(Command);           
}
void commandSplit(char *in, char **out)
{
    int argc = 0;
    out[argc++] = strtok(in, SEP);
    while(out[argc ++ ] = strtok(NULL, SEP));
#ifdef Debug 
    for(int i = 0;out[i];i ++)
        cout << i <<':' <<  out[i] << endl;
#endif
}

int execute(char* argv[])
{
    pid_t id = fork();
    if(id < 0) return -1;
    else if(id == 0) // child
    {
        int fd = 0;
        if(redir == InputRedir)
        {
            fd = open(filename, O_RDONLY);
            dup2(fd, 0);
        }
        else if(redir == OutputRedir)
        {
            fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
            dup2(fd, 1);
        } 
        else if(redir == AppendRedir)
        {
            fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0666);
            dup2(fd, 1);
        }
        // exec Command
        execvp(argv[0], argv);
	    exit(1);
    }
    else //father
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        if(rid > 0){
            lastcode = WEXITSTATUS (status);
        }
         	
    }
    return 0;
}
void cd(const char *path)
{
    chdir(path);
    char tmp[1024];
    getcwd(tmp, sizeof (tmp));
    sprintf(cwd ,  "PWD=%s", tmp);
    putenv(cwd);
}
//1 - YES, 0 - NO
int doBuildin(char* argv[])
{
    if(strcmp(argv[0], "cd") == 0)
    {
        const char *path = NULL;
        if(argv[1] == NULL) path = homepath() ;
        else path = argv[1];
        cd(path);
        return 1;
    }
    else if(strcmp(argv[0], "export") == 0)
    {
        if(argv[1] == NULL) return 1;
        strcpy(enval[envnum], argv[1]); 
        putenv(enval[envnum]);
        return 1;
    }
    else if(strcmp(argv[0], "echo") == 0)
    {
        if(argv[1] == NULL){
            cout << endl;
            return 1;
        }
        if(*(argv[1]) == '$'){
            char* val = argv[1] + 1;
            if(strcmp(val, "?") == 0)
            {
                cout << lastcode  << endl;
                lastcode = 0;
            }
            else 
            {
                const char *enval = getenv(val);
                if(enval)
                    cout << enval << endl;
                else cout << endl;
            }
        }
        else {
            cout << argv[1] << endl;
            return 1;
        }
        return 1;
    }

    return 0;
}

#define SkipSpace(pos) do{ while(isspace(*pos)) pos ++; }while(0)
  
void checkRedir(char usercommand[], int len)
{
    char*end = usercommand + len - 1;
    char *start = usercommand;
    while(end > start)
    {
        if(*end == '>')
        {
            if(*(end - 1) == '>')
            {
                *(end - 1) = '\0';
                filename = end + 1;
                SkipSpace(filename);
                redir = AppendRedir;
                break;
            }
            else 
            {
                *end = '\0';
                filename = end + 1;
                SkipSpace(filename);
                redir = OutputRedir;
                break;
            }
        }
        else if(*end == '<')
        {
            *end = '\0';
            filename = end + 1;
            SkipSpace(filename); // 如果有空格， 就跳过
            redir = InputRedir;
            break;
        }
        else 
        {
            end --;
        }
    }
}
int main()
{
    while(1)
    {
        filename = NULL;
        redir = NoneRedir;
        char userCommand[MAX_NUM];
        char* argv[SIZE];
        //1.获取命令行输入
	    int n =  getCommand(userCommand, sizeof (userCommand));
        if(n <= 0) continue;
        //1.1 检查是否发生了重定向
        checkRedir(userCommand, strlen(userCommand));
        //2.分隔命令行输入
        commandSplit(userCommand, argv);
        //3.check build-in Command  
        n = doBuildin(argv);
        if(n) continue;
        //4.执行输入
        execute(argv);
    }
    return 0;
}
